<template>
    <div class="header">
      <div class="search-box">
        <el-dropdown @command="handleCommand" trigger="click" placement="bottom" >
        <el-input v-if="showSearch" placeholder="中外文文献" v-model="searchValue" class="input-with-select" @keyup.enter.native="goSearch">
          <el-select v-model="select" slot="prepend" placeholder="检索依据" style="width: 120px">
            <el-option
                v-for="(item, index) in option"
                :key="index"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="goSearch"></el-button>
        </el-input >
        <el-dropdown-menu slot="dropdown" style="width: 750px" v-if="showPrefix" >
            <el-dropdown-item v-for="item in results" :key="item" :command="item" v-html="highlight(item)" >
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

      </div>

      <el-menu :default-active="activeIndex" mode="horizontal" @select="handleSelect">
        <el-menu-item index="1" style="font-size: 26px" @click="gotoHome">
          <!-- 白天模式 黑夜模式的logo -->
          <img v-if="mode==='black'" src="../assets/images/logo_nobackground.png" alt="logo" style="height: 40px">
          <img v-else src="../assets/images/logo_normal.png" alt="logo" style="height: 40px">
        </el-menu-item>
        <el-menu-item index="2" @click="advanceSearch" class="SearchTitle">高级搜索</el-menu-item>
        <el-menu-item index="3" @click="gotoScholar" class="SearchTitle">搜索学者</el-menu-item>

        <el-submenu index="5" style="float: right" v-if="$store.state.isLogin">
          <template slot="title">{{$store.state.user.username}}</template>
          <el-menu-item index="5-1" class="big-item" @click="gotoLib">个人图书馆</el-menu-item>
          <el-menu-item index="5-2" class="big-item" @click="gotoMySch">我的门户</el-menu-item>
          <el-menu-item index="5-3" class="big-item" @click="settings">账户设置</el-menu-item>
          <el-menu-item index="5-4" class="big-item" @click="logout">退出</el-menu-item>
        </el-submenu>
        <i v-if="$store.state.isLogin" class="el-icon-user icon"></i>
        <el-button index="5" style="float: right;margin: 12px;" type="primary" size="default" v-if="!$store.state.isLogin" @click="register">注 册</el-button>
      <el-button index="6"  style="float: right;margin: 12px;" v-if="!$store.state.isLogin" type="primary" @click="login">登 录</el-button>

      </el-menu>
    </div>
</template>

  <script>
  import user from "@/store/user";

  export default {

    name: 'Header',
    props: [ 'tag',  'input', 'options','mode','searchInHeader'],
    data() {
      return {
        showSearch: true,
        userName: 'huangzehuan',
        activeIndex: '1',
        userInfo:{},
        isLogin: false,
        select: 'main', //检索模式，默认为main
        searchValue: '', //检索内容
        showPrefix: true,
        option: [
        {
          value: "main",
          label: "主题",
        },
        {
          value: "title",
          label: "篇名",
        },
        {
          value: "abstract",
          label: "摘要",
        },
        {
          value: "field",
          label: "领域",
        },
        {
          value: "author",
          label: "作者",
        },
        {
          value: "affiliation_name",
          label: "作者单位",
        },
        {
          value: "publisher",
          label: "文献来源",
        },
        {
          value: "doi",
          label: "DOI",
        },
      ],
      };
    },
    computed:{
    },
    mounted() {
      console.log(this.$store.state.isLogin)
      console.log(this.userInfo)
      console.log(window.location.hash)
    },
  created() {
      console.log("this.$route.path");
      console.log(this.$route.path);
      console.log("this.searchInHeader");
      console.log(this.$route.meta.searchInHeader);
      if (this.$route.meta.searchInHeader==false)
        this.showSearch = false;
      else this.showSearch=true;
      //用Vuex获得全局的用户信息 如果能获取到就登录成功
      //应该是用了本地存储 可以保存上一次登录结果
      // const userInfo = user.getters.getUser(user.state());
      // if (userInfo)
      // {
      //   this.isLogin = true;
      //   this.userName = userInfo.user.username;
      // }
      // this.showSearch = true;
      const userInfo = user.state().user;
      if (userInfo)
      {
        this.isLogin = true;
        this.userName = userInfo.user.username;
      }
      switch (this.mode) {
        case 'white':
          document.documentElement.style.setProperty('--item-font-color', 'black');
          document.documentElement.style.setProperty('--background-color', 'transparent');
          document.documentElement.style.setProperty('--border-bottom', 'none');
          document.documentElement.style.setProperty('--hover-color', '#575757');
          document.documentElement.style.setProperty('--name-color', 'black');
          break;
        case 'black':
          document.documentElement.style.setProperty('--item-font-color', 'white');
          document.documentElement.style.setProperty('--background-color', 'transparent');
          document.documentElement.style.setProperty('--border-bottom', 'none');
          document.documentElement.style.setProperty('--hover-color', '#cbcbcb');
          document.documentElement.style.setProperty('--name-color', 'white');
          break;
        case 'default':
          document.documentElement.style.setProperty('--item-font-color', 'black');
          // document.documentElement.style.setProperty('--background-color', 'white');
          document.documentElement.style.setProperty('--border-bottom', '2px solid transparent');
          document.documentElement.style.setProperty('--hover-color', '#575757');
          document.documentElement.style.setProperty('--name-color', 'black');
          break;
      }
    },
    methods: {
      test()
      {
        console.log(this.$store.state.user)
        console.log(this.$store.state.isLogin)
      },
      setItem()
      {
        localStorage.setItem('islogin',true);
      },
      readItem()
      {
        this.$store.state.isLogin=localStorage.getItem('islogin');
      },

      goSearch: function () {
      if (this.searchValue === "") {
        this.$message.warning("请输入检索词！");
        return;
      }
      let routeUrl = this.$router.resolve({
        path: "/searchRes?" + this.select + "=" + this.searchValue,
      });
      window.open(routeUrl.href, "_self");
    },
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },
      gotoHome: function () {
        this.$router.push('/');
      },
      advanceSearch: function () {
        // const userInfo = user.getters.getUser(user.state());
        this.defaultMode='defalut'
        this.$router.push('/advSearch');
      },
      gotoScholar: function () {
        this.$router.push('/searchAut');
      },
      gotoCommunity: function () {
        this.$router.push('/community');
      },
      login() {
        this.$router.push('/login');
      },
      register(){
        this.$router.push('/register')
      },
      gotoLib() {
        this.$router.push('/schLib');
      },
      gotoMySch() {
        // 不重新打开窗口
        // window.open('/schPortal', '_self');
        // alert(this.sessionStorage.authorId)
        // alert("wrong")
        if(this.$store.state.user.type == 0 )
        {
          this.$router.push('/applysettle');
        }
          else
      {
        // alert(this.$store.state.user.authorId)
        let routeUrl = this.$router.resolve({
        path: '/portal',
        query: { v: this.$store.state.user.authorId }
      });
      window.open(routeUrl .href, "_self");
      }
      },
      settings() {
        this.$router.push('/settings');
      },
      logout() {
        this.$store.dispatch('clear');
        this.$message.success("退出成功！");
        sessionStorage.clear()
        setTimeout(() => {
          location.reload();
        }, 1000);
        this.$router.push('/');
      },

      highlight(src) {
      let value = src;
      let key = this.searchValue;
      if (!value || !key) return "";
      if (value.length > 100) {
        return value.slice(0, 100) + "...";
      }
      let start = value.toLowerCase().indexOf(key.toLowerCase());
      if (start !== -1) {
        return value.replace(
          value.slice(start, start + key.length),
          `<font color='#1e90ff' style='font-weight: bold'">${value.slice(
            start,
            start + key.length
          )}</font>`
        );
      } else {
        return value;
      }
    },

    handleCommand(value) {
      let routeUrl = this.$router.resolve({
        path: "/searchRes?" + this.select + "=" + value,
      });
      window.open(routeUrl.href, "_self");
    },

    getPrefix() {
      console.log("gettingPrefix");
      console.log("this.searchValue"+this.searchValue);
      console.log("this.select"+this.select);
        const formData={
              name:this.searchValue,
              normalSearchOption:this.select=="author"?"author":"main",
        }
          this.$axios({
            method:'post',
            url:'http://117.78.4.242/api/search/normalSearch/getPrefix/',
            data:JSON.stringify(formData)
          }).then(response=>{
            this.results = response.data.items;
            console.log(this.results);
            console.log(response.data)
            console.log("消息已收到")
          })
          .catch((err) => {
            console.log(err);
          });
    },
    },
  watch: {
    searchValue(newVal, oldVal) {
      if (newVal !== "" && newVal !== oldVal) this.getPrefix();
    },
    select(newVal, oldVal) {
      if (newVal !== "" && newVal !== oldVal) this.getPrefix();
    },
    results(newVal) {
      if (newVal.length > 0) this.showPrefix = true;
    },
      isLogin:{
        handler(a,b){}
      },
      mode:{}
    }

  }
  </script>


  <style scoped>

  :root {
    --item-font-color: white;
    --background-color: transparent;
    --border-bottom: 2px solid transparent;
    --hover-color: black;
    --name-color: black;
  }

  .header {
    background-color: var(--background-color);
  }

  .header .icon {
    color: var(--item-font-color);
  }

  .header .el-menu {
    height: 70px;
    padding-left: 50px;
    padding-right: 50px;
    background-color: var(--background-color);
    color: black;
  }

  .header .el-menu.el-menu--horizontal {
    border-bottom: var(--border-bottom);
  }

  .header .el-menu--horizontal >>> .el-menu-item {
    float: left;
    height: 70px;
    line-height: 70px;
    margin: 0;
    border-bottom: var(--border-bottom);
    color: var(--item-font-color);
  }

  .header >>> .el-submenu__title {
    background: transparent !important;
  }

  .header >>> .el-submenu__title {
    font-size: 16px;
    color: var(--name-color) !important;
    padding: 0 20px;
    cursor: pointer;
    transition: border-color .3s,background-color .3s,color .3s;
    box-sizing: border-box;
  }

  .header .el-icon-user {
    padding-top: 22px;
    font-size: 24px;
    float: right;
  }

  .header .el-menu--horizontal >>>.el-menu-item.is-active {
    border-bottom: 2px solid transparent;
  }

  .header .el-menu-item {
    font-size: 17px;
  }

  .header .el-menu--horizontal .el-submenu >>> .el-submenu__title {
    height: 70px;
    line-height: 70px;
    color: black;
  }

  .header .el-submenu__title {
    font-size: 16px;
    color: black;
  }

  .el-menu--horizontal >>> .el-submenu.is-active .el-submenu__title {
    border-bottom: none !important;
    color: black;
  }

  .big-item .el-menu-item li {
    line-height: 50px!important;
  }

  .login-button {
    padding: 15px;
  }

  .login-button button {
    width: 100px;
  }

  .news-link {
    cursor: pointer;
  }

  .header .search-box {
    position: absolute;
    top: 15px;
    left: 35%;
    z-index: 1;
  }
  .header .input-with-select {
    width: 500px;
  }

  .header .el-menu-item:hover {
    background: transparent !important;
    color: var(--hover-color) !important;
  }

  .header .el-menu--horizontal .el-menu-item.is-active {
    background: transparent !important;
    border-bottom: 2px solid transparent;
  }
  .SearchTitle{
    font-family: source-han-sans-simplified-c, sans-serif;
    font-weight: bold;
  }

  </style>
